package com.wtb.utils;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class XmlUtils {
	/**
	 * 写入xml文件
	 * 
	 * @param document
	 * @throws IOException
	 */
	public static void writeTo(Document document,String path) {
		try {
			OutputFormat format = OutputFormat.createPrettyPrint();
			XMLWriter writer = new XMLWriter(new FileOutputStream(path),
					format);
			writer.write(document);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			System.out.println("写入XML文件失败！");
			e.printStackTrace();
		}

	}

	/**
	 * 读取XML文件到document
	 * 
	 * @param xmlFilePath
	 * @return
	 * @throws MalformedURLException
	 * @throws FileNotFoundException
	 */

	public static Document parse2Document(InputStream inputStream)
			throws MalformedURLException, FileNotFoundException {
		SAXReader reader = new SAXReader();
		Document document = null;
		try {
			document = reader.read(inputStream);
		} catch (DocumentException e) {
			System.out.println("读取xmlFileName文件发生异常");
			e.printStackTrace();
		}
		return document;
	}
	
	/**
	 * 生成XML document
	 * 
	 * @param document
	 * @param oauthBean
	 * @throws IOException
	 */
	public static  Document createDocument(){
		Document document = DocumentHelper.createDocument();
		document.addElement("count");
		return document;
	}
	
	/**
	 * 读取所有XML内所有信息
	 * 
	 * @param document
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public static int getFromDocument(Document document){
		String count = "0";
		Node node = document.selectSingleNode("/count");
		if (node != null) {
			count = node.getStringValue();
		}
		return Integer.valueOf(count);
	}
	/**
	 * 生成XML Document
	 * @param document
	 * @param key
	 * @param value
	 * @return
	 */
	public static  Document addToXml(Document document, String count ){
		Element root = document.getRootElement();
		root.setText(count);
		return document;
	}
	
}
